package todososdados.intgraf;

import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.JMSException;
import javax.naming.NamingException;
import javax.swing.JOptionPane;
import leilaomarotojmsrmi.Lance;
import leilaomarotojmsrmi.Leilao;
import todososdados.rmi.*;


/**
 *
 * @author Alice
 */
public final class LeilaoGrafico extends javax.swing.JFrame {

    
    //variáriveis globais
    //Processo pc;
    
    private ArrayList<Leilao> leilao;
    private ArrayList<Lance>  lance;
    
    private String nome;
    private String lances ="";
    
    //Servidor s;
    //Cliente  c;
    
    ServentCli refCli;
    Registry refServNome;
    InterfaceLeiloeiro refServidor; 
    
    /**
     * Creates new form LeilaoGrafico
     */
    public LeilaoGrafico() throws JMSException, NamingException, InterruptedException, RemoteException, AlreadyBoundException, MalformedURLException, NotBoundException {
        initComponents();
        
        nome = JOptionPane.showInputDialog("Favor inserir o seu nome =)");
        
        //s = new Servidor();
        //c = new Cliente();
        //p = new Pessoa(nome);
        refCli = new ServentCli();
        
        Registry refServNome = (Registry) LocateRegistry.createRegistry(2005);
        InterfaceLeiloeiro s = new ServentLeiloeiro();
        refServNome.bind("Servidor", s); //cadastra no serviço de nomes 
        
        refServNome = (Registry) LocateRegistry.getRegistry(2005);
        refServidor = (InterfaceLeiloeiro) refServNome.lookup("Servidor");       
        
    }
    
    //inicio setter e getter LANCE E LEILAO
    public ArrayList<Lance> getLance() {
        return lance;
    }

    public void setLance(ArrayList<Lance> lance) {
        this.lance = lance;
    }

    public ArrayList<Leilao> getLeilao() {
        return leilao;
    }

    public void setLeilao(ArrayList<Leilao> leilao) {
        this.leilao = leilao;
    }
    //fim setter e getter LANCE E LEILAO
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabelaLeiloes = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jTextField2 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jLabel1.setFont(new java.awt.Font("BatangChe", 3, 24)); // NOI18N
        jLabel1.setText("Leilão Maroto!");
        jLabel1.setToolTipText("");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Leilões disponíveis:");
        jLabel2.setToolTipText("");

        tabelaLeiloes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Código", "Produto", "Valor", "Tempo", "Participar?"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Double.class, java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabelaLeiloes.getTableHeader().setReorderingAllowed(false);
        tabelaLeiloes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaLeiloesMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tabelaLeiloes);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel3.setText("Dar lance! (RMI)");
        jLabel3.setToolTipText("");

        jLabel4.setText("Código:");

        jLabel5.setText("Valor:");

        jLabel6.setText("Meta Bala!");

        jButton1.setText("LANCE");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel7.setText("LANCES EM TEMPO REAL - AI É CHIQUE EM! (JMS)");

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton2.setText("Atualizar Leilões");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Finalizar Leilão");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel7)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE)
                            .addComponent(jTextField2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 383, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 367, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jButton1))
                                .addGap(19, 19, 19)
                                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton3)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(65, 65, 65)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    //método que irá cadastrar a pessoa no leilão!!!
    private void tabelaLeiloesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaLeiloesMouseClicked
        
        if(leilao.get(tabelaLeiloes.getSelectedRow()).isCadastrado() == false)
        {
            leilao.get(tabelaLeiloes.getSelectedRow()).setCadastrado(true);
            tabelaLeiloes.setValueAt("SIM", tabelaLeiloes.getSelectedRow(), 4);
            try {
                
                    refServidor.insereListaInteresse(nome, refCli);
                   
                
            } catch (RemoteException ex) {
                Logger.getLogger(LeilaoGrafico.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }else
        {
            leilao.get(tabelaLeiloes.getSelectedRow()).setCadastrado(false);
            tabelaLeiloes.setValueAt("NÃO", tabelaLeiloes.getSelectedRow(), 4);
        }
        
    }//GEN-LAST:event_tabelaLeiloesMouseClicked

    //Método do botão dar lance!!! AQUI IRÁ CHAMAR O CÓDIGO RMI!
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        
        int    cod = Integer.parseInt(jTextField2.getText());
        double val = Double.parseDouble(jTextField1.getText());
        
        jTextField1.setText(null);
        jTextField2.setText(null);
        
        for(int i=0; i<leilao.size(); i++)
        {
            //verificação se o código existe
            if(leilao.get(i).getCodigo() == cod && leilao.get(i).getPreco() < val && leilao.get(i).isCadastrado() == true)
            {
               String palavra = this.nome + " " + String.valueOf(cod) + " " + String.valueOf(val);
                try {
                    
                    System.out.println("111");
                    refServidor.darLanceLeilao(palavra);
                } catch (RemoteException ex) {
                    Logger.getLogger(LeilaoGrafico.class.getName()).log(Level.SEVERE, null, ex);
                }                
            }
            
        }
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        preencherNovosLeiloes();
    }//GEN-LAST:event_jButton2ActionPerformed

    //Método para finalizar o LEILÃO! Este método não irá existir nas outras aplicações, pois quem pode finalizar o lance é o leiloiro. Dono do produto.
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        
        int cod = Integer.parseInt(JOptionPane.showInputDialog("Inserir o código do Leilão para finalizá-lo: "));
        double valorVencedor = 0;
        
        //varrendo o leilao para conseguir o codigo do produto e o melhor valor.
        for(int i=0; i<leilao.size(); i++){
            if(cod == leilao.get(i).getCodigo())
            {
                valorVencedor = leilao.get(i).getPreco();
            }
        }
        
        //varrendo todos os lances para que através do código do prod e maior lance possa encontrar a pessoa vencedora.
        for(int i=0; i<lance.size(); i++)
        {
            if(cod == lance.get(i).getCodigo() && valorVencedor == lance.get(i).getPreco())
            {
                try {
                    refServidor.darLanceLeilao("O Vencedor do Leilão de código: "+String.valueOf(cod)+" com o lance de R$"+String.valueOf(valorVencedor)+ " foi: "+lance.get(i).getPessoa());
                } catch (RemoteException ex) {
                    Logger.getLogger(LeilaoGrafico.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        
    }//GEN-LAST:event_jButton3ActionPerformed

    public static void main(String args[]) throws JMSException, NamingException, InterruptedException, RemoteException, AlreadyBoundException, NotBoundException, MalformedURLException {
        /*
         * Set the Nimbus look and feel
         */
        
         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LeilaoGrafico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LeilaoGrafico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LeilaoGrafico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LeilaoGrafico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        
        /*
         * Create and display the form
         */
        
        
        
        
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                    try {
                        new LeilaoGrafico().setVisible(true);
                    } catch (JMSException ex) {
                        Logger.getLogger(LeilaoGrafico.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (NamingException ex) {
                        Logger.getLogger(LeilaoGrafico.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(LeilaoGrafico.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (RemoteException ex) {
                        Logger.getLogger(LeilaoGrafico.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (AlreadyBoundException ex) {
                        Logger.getLogger(LeilaoGrafico.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (MalformedURLException ex) {
                        Logger.getLogger(LeilaoGrafico.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (NotBoundException ex) {
                        Logger.getLogger(LeilaoGrafico.class.getName()).log(Level.SEVERE, null, ex);
                    }
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTable tabelaLeiloes;
    // End of variables declaration//GEN-END:variables
    
    public void preencherNovosLeiloes()
    {
        
        for(int i=0; i<leilao.size() ;i++)
        {
            tabelaLeiloes.setValueAt(leilao.get(i).getCodigo(), i, 0);
            tabelaLeiloes.setValueAt(leilao.get(i).getNome(), i, 1);
            tabelaLeiloes.setValueAt(leilao.get(i).getPreco(), i, 2);
            tabelaLeiloes.setValueAt(leilao.get(i).getTempo(), i, 3);
            tabelaLeiloes.setValueAt("NÃO", i, 4);
        }
        
    }
    
    public void atualizarNovosLeiloes()
    {
        
        for(int i=0; i<leilao.size() ;i++)
        {
            tabelaLeiloes.setValueAt(leilao.get(i).getCodigo(), i, 0);
            tabelaLeiloes.setValueAt(leilao.get(i).getNome(), i, 1);
            tabelaLeiloes.setValueAt(leilao.get(i).getPreco(), i, 2);
            tabelaLeiloes.setValueAt(leilao.get(i).getTempo(), i, 3);
            
            if(leilao.get(i).isCadastrado() == true)
                tabelaLeiloes.setValueAt("SIM", i, 4);
            else
               tabelaLeiloes.setValueAt("NÃO", i, 4);
   
        }
        
    }
    
    //Método que atualiza a Área dos lances!!!
    public void mostrarLancesArea()
    {
        
        for(int i=0; i<leilao.size() ;i++)
        {
            if(leilao.get(i).isCadastrado() == true && leilao.get(i).getCodigo() == lance.get(lance.size()-1).getCodigo())
            {
                this.lances = this.lances + "Pessoa: "+ lance.get(lance.size()-1).getPessoa()+ " - Código Produto: " + String.valueOf(lance.get(lance.size()-1).getCodigo()) + " - Lance: R$" + String.valueOf(lance.get(lance.size()-1).getPreco())+"\n";
                jTextArea1.setText(this.lances);
            }
        }
        
    }
   
   //Método final - Leilão irá receber o novo valor (sem o lance cancelado)
   public void encerrarLeilao(ArrayList<Leilao> leilao)
   {
       this.leilao = leilao;
       limparTabela();
       atualizarNovosLeiloes();
   }
    
   //Método somente para limpar a tabela.
   public void limparTabela()
   {
       for(int i=0; i<tabelaLeiloes.getRowCount() ;i++)
       {
            tabelaLeiloes.setValueAt(null, i, 0);
            tabelaLeiloes.setValueAt(null, i, 1);
            tabelaLeiloes.setValueAt(null, i, 2);
            tabelaLeiloes.setValueAt(null, i, 3);
            tabelaLeiloes.setValueAt(null, i, 4);
       }
   }
   
}
